package cn.icatw.gulimall.cart.service.impl;

import cn.icatw.common.utils.R;
import cn.icatw.gulimall.cart.feign.ProductFeignService;
import cn.icatw.gulimall.cart.interceptor.CartInterceptor;
import cn.icatw.gulimall.cart.service.CartService;
import cn.icatw.gulimall.cart.vo.CartItemVo;
import cn.icatw.gulimall.cart.vo.CartVo;
import cn.icatw.gulimall.cart.vo.SkuInfoVo;
import cn.icatw.gulimall.cart.vo.UserInfoTo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * @author icatw
 * @date 2022/3/23
 * @email 762188827@qq.com
 * @apiNote
 */
@Service
@Slf4j
public class CartServiceImpl implements CartService {
    private final String CART_PREFIX = "gulimall:cart:";
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    ProductFeignService productFeignService;
    @Autowired
    ThreadPoolExecutor executor;

    /**
     * 添加到购物车
     *
     * @param skuId sku id
     * @param num   商品数
     * @return {@link CartItemVo}
     */
    @Override
    public CartItemVo addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        //先在redis中查找是否已存在此购物项，若存在，则添加商品数量
        //添加购物项

        String res = (String) cartOps.get(skuId.toString());
        if (StringUtils.isEmpty(res)) {
            //购物车无此商品，添加新商品
            //2、添加新商品到购物车
            CartItemVo cartItemVo = new CartItemVo();
            CompletableFuture<Void> getSkuInfoTask = CompletableFuture.runAsync(() -> {
                //1、远程查询当前要添加的商品的信息
                R skuInfo = productFeignService.getSkuInfo(skuId);
                SkuInfoVo data = skuInfo.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                });
                cartItemVo.setCheck(true);
                cartItemVo.setCount(num);
                cartItemVo.setImage(data.getSkuDefaultImg());
                cartItemVo.setTitle(data.getSkuTitle());
                cartItemVo.setPrice(data.getPrice());
                cartItemVo.setSkuId(skuId);
            }, executor);
            //3、远程查询sku的组合信息
            CompletableFuture<Void> getSkuAttrValues = CompletableFuture.runAsync(() -> {
                List<String> skuSaleAttrValues = productFeignService.getSkuSaleAttrValues(skuId);
                cartItemVo.setSkuAttrValues(skuSaleAttrValues);
            }, executor);
            //异步编排
            CompletableFuture.allOf(getSkuInfoTask, getSkuAttrValues).get();
            String json = JSON.toJSONString(cartItemVo);
            //将购物车数据存放到redis中
            cartOps.put(skuId.toString(), json);
            return cartItemVo;
        } else {
            //    购物车有此商品，修改数量即可
            CartItemVo cartItemVo = JSON.parseObject(res, CartItemVo.class);
            //以redis中存放的商品数量加前端传过来的商品数量
            cartItemVo.setCount(cartItemVo.getCount() + num);
            //redis中存放json
            cartOps.put(skuId.toString(), JSON.toJSONString(cartItemVo));
            return cartItemVo;
        }
    }

    @Override
    public CartItemVo getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String str = (String) cartOps.get(skuId.toString());

        return JSON.parseObject(str, CartItemVo.class);
    }

    @Override
    public CartVo getCart() throws ExecutionException, InterruptedException {
        //区分是否登录
        //得到用户信息判断是否登录
        /*
         登录状态，存在userId
         未登陆，存在user-key
         */
        CartVo cartVo = new CartVo();
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        //临时购物车key
        String tempCartKey = CART_PREFIX + userInfoTo.getUserKey();
        log.info("临时用户key："+tempCartKey);
        //登陆用户购物车key
        String cartKey = CART_PREFIX + userInfoTo.getUserId();
        if (userInfoTo.getUserId() != null) {
            //1、登陆
            BoundHashOperations<String, Object, Object> hashOps = stringRedisTemplate.boundHashOps(cartKey);
            //2、如果登陆之前临时购物车有数据需要将其合并【合并购物车】
            //临时购物车的数据
            List<CartItemVo> tempCartItems = getCartItems(tempCartKey);
            if (tempCartItems != null && tempCartItems.size() > 0) {
                //临时购物车有数据，需要合并
                for (CartItemVo tempCartItem : tempCartItems) {
                    addToCart(tempCartItem.getSkuId(), tempCartItem.getCount());
                }
                //    合并完成，清除临时购物车数据
                //hashOps.delete(CART_PREFIX + userInfoTo.getUserKey());
                clearCart(tempCartKey);
            }
            //    3、获取登陆后的购物车【包含合并的购物车数据，合并操作已经在上面完成】
            List<CartItemVo> cartItems = getCartItems(cartKey);
            cartVo.setItems(cartItems);
        } else {
            //2、没登录
            //获取临时购物车的所有购物项
            List<CartItemVo> cartItems = getCartItems(tempCartKey);
            cartVo.setItems(cartItems);
        }
        return cartVo;
    }

    @Override
    public void clearCart(String cartKey) {
        stringRedisTemplate.delete(cartKey);
    }

    @Override
    public void checkItem(Long skuId, Integer check) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        CartItemVo cartItem = getCartItem(skuId);
        cartItem.setCheck(check == 1);
        String json = JSON.toJSONString(cartItem);
        cartOps.put(skuId.toString(), json);
    }

    @Override
    public void countItem(Long skuId, Integer num) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        CartItemVo cartItem = getCartItem(skuId);
        cartItem.setCount(num);
        String json = JSON.toJSONString(cartItem);
        cartOps.put(skuId.toString(), json);
    }

    @Override
    public void deleteItem(@NotNull Long deleteId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.delete(deleteId.toString());
    }

    @Override
    public List<CartItemVo> getCurrentUserCartItems() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if (userInfoTo.getUserId() == null) {
            //未登陆，直接返回
            return null;
        } else {
            List<CartItemVo> cartItems = getCartItems(CART_PREFIX + userInfoTo.getUserId());
            //获取所有被选中的购物项
            if (cartItems != null) {
                return cartItems.stream()
                        .filter(CartItemVo::getCheck)
                        .peek(item -> {
                            //TODO 更新下单价格为最新商品价格 bug 无法批量购买
                            //需要更新为最新价格，远程查询
                            BigDecimal price = productFeignService.getPrice(item.getSkuId());
                            item.setPrice(price);
                        })
                        .collect(Collectors.toList());
            }
        }
        return null;
    }


    /**
     * 获取到需要操作的购物车
     *
     * @return {@link BoundHashOperations}<{@link String}, {@link Object}, {@link Object}>
     */
    private BoundHashOperations<String, Object, Object> getCartOps() {
        //得到用户信息，判断是否登录
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        //存放到redis中的购物车key gulimall:cart:“用户id"
        String cartKey = "";

        if (userInfoTo.getUserId() != null) {
            //登录
            cartKey = CART_PREFIX + userInfoTo.getUserId();
        } else {
            cartKey = CART_PREFIX + userInfoTo.getUserKey();
        }
        //绑定redis hash值，针对这个hash进行crud
        return stringRedisTemplate.boundHashOps(cartKey);
    }

    /**
     * 获取指定购物车的购物项（临时用户或登陆用户）
     *
     * @param cartKey 车钥匙
     * @return {@link List}<{@link CartItemVo}>
     */
    private List<CartItemVo> getCartItems(String cartKey) {
        BoundHashOperations<String, Object, Object> hashOps = stringRedisTemplate.boundHashOps(cartKey);
        List<Object> values = hashOps.values();
        if (values != null && values.size() > 0) {
            return values.stream().map((obj) -> {
                String str = (String) obj;

                return JSON.parseObject(str, CartItemVo.class);
            }).collect(Collectors.toList());
        }
        return null;
    }
}
